﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Tracking.Data.Model.Implementation;
using Tracking.Data.Model.Interfaces;
using Tracking.Web.Models;

namespace Tracking.Web.Controllers
{
    public class AccountController : Controller
    {
        IUserRepository userRepository;

        public AccountController()
            : this(new UserRepository())
        {

        }

        public AccountController(IUserRepository userRepository)
        {
            this.userRepository = userRepository;
        }

        //
        // GET: /Account/
        public ActionResult Index()
        {

            return View();
        }

        [HttpGet]
        public ActionResult Login()
        {

            return View();
        }

        [HttpPost]
        public ActionResult Login(LoginModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var user = userRepository.Login(model.Username, model.Password);

                    if (user != null)
                    {
                        return RedirectToAction("Index", "Shipment");
                    }
                    else
                    {
                        AddError("invalid username/password");
                    }
                }
                catch (Exception ex)
                {
                    AddError(ex.Message);
                }
            }
            return View(model);
        }

        private void AddError(string message)
        {
            ViewBag.Error = message;
        }
    }
}
